package tree.binary;

import tree.Traversal;

/**
 * 递归遍历
 *
 * @Author: wangxiaonan
 * @Date: 2019/3/5
 **/
public class RecursionTraversal implements Traversal<BinaryTreeNode> {


    /**
     * ---------- 前序遍历 ----------
     * 841356972
     * ---------- 中序遍历 ----------
     * 134658729
     * ---------- 后序遍历 ----------
     * 316542798
     */
    public static void main(String[] args) {
        RecursionTraversal tr = new RecursionTraversal();
        BinaryTreeNode root = BinaryTreeNode.initBinaryTree();
        System.out.println("\n---------- 前序遍历 ----------");
        tr.preOrderTraversal(root);
        System.out.println("\n---------- 中序遍历 ----------");
        tr.inOrderTraversal(root);
        System.out.println("\n---------- 后序遍历 ----------");
        tr.postOrderTraversal(root);
        System.out.println();
    }

    @Override
    public void preOrderTraversal(BinaryTreeNode tree) {
        if (tree.getData() != null) {
            this.print(tree.getData());
        }
        if (tree.getLeft() != null) {
            preOrderTraversal(tree.getLeft());
        }
        if (tree.getRight() != null) {
            preOrderTraversal(tree.getRight());
        }
    }

    @Override
    public void inOrderTraversal(BinaryTreeNode tree) {
        if (tree.getLeft() != null) {
            inOrderTraversal(tree.getLeft());
        }
        if (tree.getData() != null) {
            this.print(tree.getData());
        }
        if (tree.getRight() != null) {
            inOrderTraversal(tree.getRight());
        }
    }

    @Override
    public void postOrderTraversal(BinaryTreeNode tree) {
        if (tree.getLeft() != null) {
            postOrderTraversal(tree.getLeft());
        }
        if (tree.getRight() != null) {
            postOrderTraversal(tree.getRight());
        }
        if (tree.getData() != null) {
            this.print(tree.getData());
        }
    }

    public void print(Object data) {
        System.out.print(data.toString());
    }

}
